<template>
    <div class="schema-view">
        <search-panel :schema="tableSchema" :api="api" :buttons="tableConfig?.rowButtons ?? []"
            v-if="searchSchema?.properties && Object.keys(searchSchema.properties).length > 0"
            @search="onSearch"></search-panel>
        <table-panel :buttons="tableConfig?.headerButtons ?? []" @operate="onTableOperate"
            ref="tablePanelRef"></table-panel>
        <component v-for="(item, key) in components" :key="key" :is="ComponentConfig[key].component" :name="item.name"
            ref="comListRef" @command="onComponentCommand"></component>
    </div>
</template>

<script setup>
import { provide, ref } from 'vue'
import SearchPanel from './complex-view/search-panel/search-panel.vue'
import TablePanel from './complex-view/table-panel/table-panel.vue'
import { useSchema } from './hooks/schema'
import ComponentConfig from './components/component-config'

const comListRef = ref([])
const tablePanelRef = ref(null)

const { api, tableSchema, tableConfig, searchSchema, searchConfig, components } = useSchema()
const apiParams = ref({})
provide('schemaViewData', {
    api,
    tableSchema,
    tableConfig,
    searchSchema,
    searchConfig,
    apiParams,
    components,
})

const onSearch = (searchValueObj) => {
    apiParams.value = searchValueObj
}

const showComponent = ({ btnConfig, rowData }) => {
    const { comName } = btnConfig.eventOption;
    if (!comName) { return; }

    const comRef = comListRef.value.find(item => item.name === comName);
    if (!comRef || typeof comRef.show !== 'function') { return; }

    comRef.show(rowData);
}
const EventHandleMap = {
    showComponent: showComponent
}

// 响应组件事件
const onComponentCommand = (data) => {
    if (data === 'loadTableData') {
        tablePanelRef.value.loadTableData();
    }
}

const onTableOperate = ({ btnConfig, rowData }) => {
    const { eventKey } = btnConfig
    const eventHandle = EventHandleMap[eventKey]
    if (eventHandle) {
        eventHandle({ btnConfig, rowData })
    }
}
</script>

<style scoped lang="less">
.schema-view {
    display: flex;
    flex-direction: column;
    height: 100%;
    width: 100%;
}
</style>